package com.kun.peng.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kun.peng.exception.BadRequestException;
import com.kun.peng.exception.EntityExistException;
import com.kun.peng.security.service.UserCacheClean;
import com.kun.peng.system.domain.Menu;
import com.kun.peng.system.domain.Role;
import com.kun.peng.system.domain.User;
import com.kun.peng.system.service.mapstruct.RoleMapStruct;
import com.kun.peng.system.service.mapstruct.RoleSmallMapStruct;
import com.kun.peng.utils.*;
import com.kun.peng.mybatis.base.IBaseService;
import com.kun.peng.system.mapper.RoleMapper;
import com.kun.peng.system.service.MenuService;
import com.kun.peng.system.service.RoleService;
import com.kun.peng.system.service.UserService;
import com.kun.peng.system.service.dto.RoleDto;
import com.kun.peng.system.service.dto.RoleQueryCriteria;
import com.kun.peng.system.service.dto.RoleSmallDto;
import com.kun.peng.system.service.dto.UserDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created on 2021/11/19.
 *
 * @author xuebaopeng
 * Description
 */
@Slf4j
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "role")
public class RoleServiceImpl extends IBaseService<RoleMapper, Role> implements RoleService {

    private final RoleSmallMapStruct roleSmallMapper;

    private final RoleMapStruct roleMapStruct;
    @Resource
    private UserService userService;
    @Resource
    private MenuService menuService;
    private final RedisUtils redisUtils;
    private final UserCacheClean userCacheClean;

    @Override
    public List<RoleDto> queryAll() {
         return roleMapStruct.toDto(getBaseMapper().selectList(Wrappers.lambdaQuery(Role.class).orderByAsc(Role::getLevel)));
    }

    @Override
    public RoleDto findRoleById(long id) {
        Role role = findById(id).orElseGet(Role::new);
        ValidationUtil.isNull(role.getId(), "Role", "id", id);
        return roleMapStruct.toDto(role);
    }

    @Override
    public void updateMenu(Role resources, RoleDto roleDTO) {
        Role role = roleMapStruct.toEntity(roleDTO);
        List<User> users = userService.findByRoleId(role.getId());
        // 更新菜单
        role.setMenus(resources.getMenus());
        delCaches(resources.getId(), users);
        getBaseMapper().deleteById(role.getId());
        save(role);
    }

    @Override
    public List<RoleDto> queryAll(RoleQueryCriteria criteria) {
        LambdaQueryWrapper<Role> query = new QueryWrapper<Role>().lambda();
        List<Role> roles=getBaseMapper().selectList(query);
        roles.forEach(role -> {
            role.setMenus(menuService.selectMenusByRoleId(role.getId()));
        });
        return roleMapStruct.toDto(roles);
    }



    @Override
    public List<Role> findInMenuId(List<Long> menuIds) {
        return getBaseMapper().findInMenuId(menuIds);
    }

    @Override
    public List<RoleSmallDto> findByUsersId(Long id) {
        return roleSmallMapper.toDto(new ArrayList<>(getBaseMapper().findByUserId(id)));
    }

    @Override
    @Cacheable(key = "'auth:' + #p0.id")
    public List<GrantedAuthority> mapToGrantedAuthorities(UserDto user) {
        Set<String> permissions = new HashSet<>();
        // 如果是管理员直接返回
        if (user.getIsAdmin()) {
            permissions.add("admin");
            return permissions.stream().map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }
        Set<Role> roles = getBaseMapper().findByUserId(user.getId());
        permissions = roles.stream().flatMap(role -> role.getMenus().stream())
                .filter(menu -> StringUtils.isNotBlank(menu.getPermission()))
                .map(Menu::getPermission).collect(Collectors.toSet());
        return permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public void untiedMenu(Long menuId) {
        // 更新菜单
        getBaseMapper().untiedMenu(menuId);
    }

    @Override
    public void download(List<RoleDto> roles, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RoleDto role : roles) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("角色名称", role.getName());
            map.put("角色级别", role.getLevel());
            map.put("描述", role.getDescription());
            map.put("创建日期", role.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Role resources) {
        if (getBaseMapper().findByName(resources.getName()) != null) {
            throw new EntityExistException(Role.class, "username", resources.getName());
        }
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Role resources) {
        Role role = findById(resources.getId()).orElseGet(Role::new);
        ValidationUtil.isNull(role.getId(), "Role", "id", resources.getId());

        Role role1 = getBaseMapper().findByName(resources.getName());

        if (role1 != null && !role1.getId().equals(role.getId())) {
            throw new EntityExistException(Role.class, "username", resources.getName());
        }
        role.setName(resources.getName());
        role.setDescription(resources.getDescription());
        role.setDataScope(resources.getDataScope());
        role.setDepts(resources.getDepts());
        role.setLevel(resources.getLevel());
        updateById(role);
        // 更新相关缓存
        delCaches(role.getId(), null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            // 更新相关缓存
            delCaches(id, null);
        }
        getBaseMapper().deleteBatchIds(ids);
    }

    @Override
    public void verification(Set<Long> ids) {
        if (getBaseMapper().countByRoles(ids) > 0) {
            throw new BadRequestException("所选角色存在用户关联，请解除关联再试！");
        }
    }

    @Override
    public int countByDepts(Set<Long> deptIds) {
        return getBaseMapper().countByDepts(deptIds);
    }

    /**
     * 清理缓存
     * @param id /
     */
    public void delCaches(Long id, List<User> users) {
        try {
            users = CollectionUtil.isEmpty(users) ? userService.findByRoleId(id) : users;
            if (CollectionUtil.isNotEmpty(users)) {
                users.forEach(item -> userCacheClean.cleanUserCache(item.getUsername()));
                Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet());
                redisUtils.delByKeys(CacheKey.DATA_USER, userIds);
                redisUtils.delByKeys(CacheKey.MENU_USER, userIds);
                redisUtils.delByKeys(CacheKey.ROLE_AUTH, userIds);
            }
            redisUtils.del(CacheKey.ROLE_ID + id);
        }catch (Exception e){
            log.error("清理角色缓存失败",e);
        }

    }
}
